package com.example.rabbitorderproduct.controller;

import com.example.rabbitorderproduct.bean.OrderBean;
import com.example.rabbitorderproduct.dao.OrderDao;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Optional;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/6/29
 * @Version 1.0.0
 */
@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderDao orderDao;

    @RequestMapping("/create")
    public ModelAndView createOrder(Model model){

        String orderNo = System.currentTimeMillis() + "";
        //创建订单
        OrderBean orderBean = new OrderBean();
        orderBean.setOrderNo(orderNo);
        orderBean.setStatus(1);
        orderDao.save(orderBean);
        Message message = new Message(orderNo.getBytes());
        rabbitTemplate.send("ex.go","go",message);
        ModelAndView order = new ModelAndView("order");
        order.addObject("orderNo",orderNo);
        return order;
    }

    @PostMapping("/pay")
    public String pay(Model model,String orderNo){
        OrderBean orderBean = new OrderBean();
        orderBean.setOrderNo(orderNo);
        Optional<OrderBean> one = orderDao.findOne(Example.of(orderBean));
        OrderBean orderBean1 = one.get();
        //订单超时
        if(orderBean1.getStatus().equals(2)){
            model.addAttribute("orderNo",orderBean.getOrderNo());
            model.addAttribute("status","订单超时");
            return "timeout";
        }else{
            //付款成功
            orderBean.setStatus(3);
            orderDao.saveAndFlush(orderBean);
            return "suc";
        }
    }
}
